//
//  HomePageUserLikeListViewController.m
//  ShowYork
//
//  Created by hxh on 2020/12/21.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "HomePageUserLikeListViewController.h"
#import "HomePageDetailViewController.h"
#import "HomePageUserLikeListCell.h"
#import "HomePageItemModel.h"
@interface HomePageUserLikeListViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate>
@property (nonatomic,strong)UICollectionView *collectionView;
@property (nonatomic,copy)void(^scrollCallback)(UIScrollView *scrollView);
@property (nonatomic,assign)NSInteger page;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,assign)int totalCount;
@property (nonatomic,strong)UIView *noDataView;
@property (nonatomic,strong)UIImageView *noDataImgView;
@property (nonatomic,strong)UILabel *noDateLb;

@property (nonatomic,strong)UIView *navView;
@property (nonatomic,strong)UILabel *navCountLb;
@property (nonatomic,strong)UILabel *navTitleLb;
@property (nonatomic,strong)UIView *line;

@end

@implementation HomePageUserLikeListViewController

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
   
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    blackLineImageView.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    blackLineImageView.hidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    [self registNote];
    [self showDataLoadState];
    [self loadDataSource];
    // Do any additional setup after loading the view.
}

- (void)setUI{
    
    [MobClick event:@"mine_liked_show"];
    
    self.navView = [[UIView alloc]init];
    self.navTitleLb = [[UILabel alloc]init];
    self.navTitleLb.text = @"我赞过的";
    self.navTitleLb.textColor = RGBA(35, 24, 21, 1);
    self.navTitleLb.font = [UIFont boldSystemFontOfSize:18];
    [self.navView addSubview:self.navTitleLb];
    
    self.navCountLb = [[UILabel alloc]init];
    self.navCountLb.textColor = RGBA(35, 24, 21, 1);
    self.navCountLb.font = font(12);
    [self.navView addSubview:self.navCountLb];
    
    [self.navTitleLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.navView);
    }];
    [self.navCountLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.navTitleLb);
        make.left.equalTo(self.navTitleLb.mas_right).offset(2);
    }];
    
    self.navigationItem.titleView = self.navView;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    
    CGFloat margin = 8.0f;
    
    CGFloat itemW = (kScreenW - 4 * margin)/3;
    CGFloat itemH = itemW/3*4;
    layout.itemSize = CGSizeMake(itemW, itemH);
    layout.minimumLineSpacing = 8;
    layout.minimumInteritemSpacing = 0;
    layout.sectionInset = UIEdgeInsetsMake(8, 8,0, 8);
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.collectionView];
    
    if (@available(iOS 11.0,*)) {
        self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11,*)) {
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft);
            make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight);
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        }else{
            make.left.equalTo(self.view.mas_left);
            make.right.equalTo(self.view.mas_right);
            make.bottom.equalTo(self.view.mas_bottom);
        }
        make.top.equalTo(self.view.mas_top);
    }];
    
    [self.collectionView registerClass:[HomePageUserLikeListCell class] forCellWithReuseIdentifier:@"HomePageUserLikeListCell"];
    
    
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    __weak typeof(self)weakSelf = self;
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page = 1;
        [weakSelf loadDataSource];
    }];
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.page++;
        [weakSelf loadDataSource];
    }];
    
    
    [footer setTitle:@"—— 没有更多了 ——" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = font(10);
    footer.stateLabel.textColor = RGBA(153, 153, 153, 1);
    footer.hidden = YES;
    self.collectionView.mj_header = header;
    self.collectionView.mj_footer = footer;
    
    
    self.noDataView = [[UIView alloc]init];
    self.noDataView.backgroundColor = [UIColor whiteColor];
    self.noDataView.hidden = YES;
    [self.view addSubview:self.noDataView];
    
    [self.noDataView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
   
    self.noDataImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"mine_noList_tag"]];
    [self.noDataView addSubview:self.noDataImgView];
    
    [self.noDataImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.view).offset(-kNavBarHeight - 50);
        make.centerX.equalTo(self.view);
    }];
    
    self.noDateLb = [[UILabel alloc]init];
    self.noDateLb.text = @"还没有赞过的内容，快去找好友互动吧～";
    self.noDateLb.textColor = C153;
    self.noDateLb.font = font(12);
    self.noDateLb.textAlignment = NSTextAlignmentCenter;
    [self.noDataView addSubview:self.noDateLb];
    [self.noDateLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.noDataView);
        make.top.equalTo(self.noDataImgView.mas_bottom).offset(12);
    }];
    
    self.line = [[UIView alloc]init];
    self.line.backgroundColor = RGBA(240, 240, 240, 1);
    [self.view addSubview:self.line];
    [self.line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.height.mas_equalTo(0.5);
    }];
    
    
    
    self.page = 1;
    
    
}
- (void)loadDataSource{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = self.userId;
    param[@"loginId"] = [RPAppManager getCustomerId];
    param[@"pageIndex"] = @(self.page);
    param[@"pageSize"] = @30;
    param[@"md5"] = [RPAppManager md5StrWithApi:GetLikePost];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetLikePost) parames:param success:^(id responseObj) {
        [self hideDataLoadLoadState];
        if (self.page == 1) {
            self.dataArray = [HomePageItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]];
        }else{
            [self.dataArray addObjectsFromArray:[HomePageItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]]];
        }
        
        CGFloat total = [responseObj[RESPONSE][TOTAL] floatValue];
        
        NSString *title = @"";
        
        if (total >= 10000) {
            NSInteger count = total;
            if (count % 1000 == 0) {
                count += 1;
            }
            title = [NSString stringWithFormat:@"(%@w)",[RPAppManager notRounding:count/10000.0f afterPoint:1]];
        }else{
            title = [NSString stringWithFormat:@"(%i)",(int)total];
        }
        self.navCountLb.text = title;
        
        
        if ([self.collectionView.mj_footer isRefreshing]) {
            [self.collectionView.mj_footer endRefreshing];
        }
        if ([self.collectionView.mj_header isRefreshing]) {
            [self.collectionView.mj_header endRefreshing];
        }
        
        self.collectionView.mj_footer.hidden = self.dataArray.count == 0;
        CGFloat bottom = self.collectionView.mj_insetB;
        if (self.dataArray.count == [responseObj[RESPONSE][TOTAL] intValue]) {
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
            if (self.collectionView.mj_footer.cl_height == 44.0f) {
                self.collectionView.mj_footer.cl_height = 138.0f;
                if (bottom == 44.0f || bottom == GK_SAVEAREA_BTM + 44.0f) {
                    self.collectionView.mj_insetB = 138.0f;
                }
            }
        }else{
            [self.collectionView.mj_footer resetNoMoreData];
            if (self.collectionView.mj_footer.cl_height == 138.0f) {
                self.collectionView.mj_footer.cl_height = 44.0f;
                if (bottom == 138.0f) {
                    self.collectionView.mj_insetB = 44.0f;
                }
            }
        }
        self.totalCount = [responseObj[RESPONSE][TOTAL] intValue];
        
        
        
        [self.collectionView reloadData];
        
    } failure:^(id error) {
        [self hideDataLoadLoadState];
        if ([self.collectionView.mj_footer isRefreshing]) {
            [self.collectionView.mj_footer endRefreshing];
        }
        
        if ([self.collectionView.mj_header isRefreshing]) {
            [self.collectionView.mj_header endRefreshing];
        }
        self.page--;
    }];
}
- (void)registNote{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteItem:) name:@"deleteHomePageItem" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateLikeList:) name:@"updateItemListSource" object:nil];
}

- (void)deleteItem:(NSNotification *)note{
    HomePageItemModel *itemModel = note.userInfo[@"data"];
    __block NSInteger index = -1;
    [self.dataArray enumerateObjectsUsingBlock:^(HomePageItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([itemModel.postId isEqualToNumber:obj.postId]) {
            index = idx;
            *stop = YES;
        }
    }];
    if (index != -1) {
        [self.dataArray removeObjectAtIndex:index];
        self.totalCount--;
        if (self.dataArray.count < 30 && self.dataArray.count != self.totalCount) {
            self.page++;
            [self loadDataSource];
        }else{
            [self.collectionView reloadData];
        }
     
    }
}

- (void)updateLikeList:(NSNotification *)note{
    HomePageItemModel *itemModel = note.userInfo[@"data"];
    __block NSInteger index = -1;
    [self.dataArray enumerateObjectsUsingBlock:^(HomePageItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.postId isEqualToNumber:itemModel.postId]) {
            index = idx;
            *stop = YES;
        }
    }];
    
    // 判断当前对象点赞并且不在当前list中
    if (itemModel.isLike && index == -1) {
        // 数量+1
        self.totalCount++;
        // 插入首个位置
        [self.dataArray insertObject:itemModel atIndex:0];
    // 取消点赞 并且在当前list中
    }else if (!itemModel.isLike && index != -1) {
        // 数量-1
        self.totalCount--;
        // 移除对象
        [self.dataArray removeObjectAtIndex:index];
    }
    
    NSString *title = @"";
    
    if (self.totalCount >= 10000) {
        NSInteger count = self.totalCount;
        if (count % 1000 == 0) {
            count += 1;
        }
        title = [NSString stringWithFormat:@"(%@w)",[RPAppManager notRounding:count/10000.0f afterPoint:1]];
    }else{
        title = [NSString stringWithFormat:@"(%i)",self.totalCount];
    }
    self.navCountLb.text = title;
    
    if (self.dataArray.count == 0 && self.totalCount != 0) {
        self.page++;
        [self loadDataSource];
    }else{
        if (self.dataArray.count != self.totalCount) {
            [self.collectionView.mj_footer resetNoMoreData];
        }
        [self.collectionView reloadData];
    }
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    self.noDataView.hidden = self.dataArray.count != 0;
    self.collectionView.mj_footer.hidden = self.dataArray.count == 0;
    return self.dataArray.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    HomePageUserLikeListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HomePageUserLikeListCell" forIndexPath:indexPath];
    [cell setModel:self.dataArray[indexPath.item]];
    return cell;
}

- (UIView *)listView {
    return self.view;
}

- (UIScrollView *)listScrollView {
    return self.collectionView;
}


- (void)listViewDidScrollCallback:(void (^)(UIScrollView *))callback {
    self.scrollCallback = callback;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    !self.scrollCallback ?: self.scrollCallback(scrollView);
   
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[kXHItemType] = @(XHPageDetailItemTypeMix);
    param[kXHPlatformType] = @(XHPageDetailPlatformTypeNormal);
    param[kXHLikedUserId] = self.userId;
    param[kXHShowUserInfo] = @(YES);
    param[kXHCurrentIndex] = @(indexPath.item);
    param[kXHCurrentPage] = @(self.page);
    param[kXHListSource] = self.dataArray;
    param[kXHUserCreateTime] = @(YES);
    
    HomePageDetailViewController *dtlVC = [[HomePageDetailViewController alloc]initWithConfigInfo:param];
    [self.navigationController pushViewController:dtlVC animated:YES];
}


- (UIImageView *)findHairlineImageViewUnder:(UIView *)view{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}


@end
